import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    nameValue: '',
  },
  onLoad(options) {
    const { name } = options;
    this.setData({
      nameValue: decodeURIComponent(name || ''),
    });
  },
  onSubmit() {
    const { nameValue } = this.data;
    
    if (!nameValue.trim()) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入昵称',
        theme: 'warning'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    if (!token) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请先登录',
        theme: 'error'
      });
      return;
    }

    // 更新昵称
    wx.request({
      url: 'http://localhost:8080/api/wx/profile',
      method: 'PUT',
      header: {
        'Authorization': token,
        'content-type': 'application/json'
      },
      data: {
        nickName: nameValue.trim()
      },
      success: (res) => {
        if (res.statusCode === 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '昵称更新成功',
            theme: 'success'
          });
          
          // 更新本地用户信息
          if (res.data.userInfo) {
            wx.setStorageSync('userInfo', res.data.userInfo);
          }
          
          setTimeout(() => {
            wx.navigateBack();
          }, 800);
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.data.message || '更新失败',
            theme: 'error'
          });
        }
      },
      fail: (err) => {
        console.error('更新昵称失败:', err);
        Toast({
          context: this,
          selector: '#t-toast',
          message: '网络请求失败',
          theme: 'error'
        });
      }
    });
  },
  clearContent() {
    this.setData({
      nameValue: '',
    });
  },
});
